package me.uniauto.handler;

import me.uniauto.notification.AsyncNotification;
import me.uniauto.util.AppUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 异常捕获
 *
 */
@Component
public class ExceptionHandler implements HandlerExceptionResolver {

    @Autowired
    private AsyncNotification asyn;

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
                                         Exception ex) {
        //logger.error("异常捕获", ex);
        //其他的错误才发邮件
        String uri = request.getRequestURI();
        StringWriter stringWriter = new StringWriter();
        ex.printStackTrace(new PrintWriter(stringWriter));
        String subject = "亲,方法[ " + uri + " ]报错啦,抓紧时间看看呗!";
        String localIp = AppUtil.INSTANCE.getLocalIp();
        StringBuffer contentinfo=new StringBuffer();
        contentinfo.append("["+localIp+"]");
        contentinfo.append("----");
        contentinfo.append("----");
        String content = "\n机器的ip : " + localIp +
                "<br/><br/>\n报错时间 : " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) +
                "<br/><br/>\n方法的名称 : " + uri +
                "<br/><br/>\n===========================异常如下:===========================<br/><br/>" + stringWriter.getBuffer().toString();

        asyn.sendEmail("yangyujing@uniauto.me", subject, content);

        return new ModelAndView("error");//未知异常
    }
}
